<template>
  <a-modal width="600px" v-model:visible="visible" :title="title" unmountOnExit @before-ok="onOk">
    <a-form ref="formRef" :model="form" size="medium" auto-label-width>
      <a-form-item
        label="菜单名称"
        field="name"
        :validate-trigger="['change', 'input', 'blur', 'focus']"
        :rules="[{ required: true, maxLength: 5, message: '菜单名称必填且需要小于5个字' }]"
      >
        <a-input placeholder="请输入菜单名称" v-model="form.name" allow-clear></a-input>
      </a-form-item>
      <a-form-item label="菜单类型" field="type">
        <a-radio-group v-model="form.type">
          <a-radio value="click">点击事件</a-radio>
          <a-radio value="view">打开网页</a-radio>
          <a-radio value="miniprogram">打开小程序</a-radio>
          <a-radio value="empty" v-if="form.pId == 0 || !form.pId">打开二级菜单</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="事件标识" field="eventKey" v-if="form.type == 'click'">
        <a-input placeholder="允许输入数字/字母和下划线的组合" v-model="form.eventKey" allow-clear></a-input>
      </a-form-item>
      <a-form-item label="appId" field="appId" v-if="form.type == 'miniprogram'">
        <a-input placeholder="请输入小程序appId" v-model="form.appId" allow-clear></a-input>
      </a-form-item>
      <a-form-item label="路径" field="miniPath" v-if="form.type == 'miniprogram'">
        <a-input placeholder="请输入小程序路径" v-model="form.miniPath" allow-clear></a-input>
      </a-form-item>
      <a-form-item label="页面URL" field="viewUrl" v-if="form.type == 'miniprogram' || form.type == 'view'">
        <a-input placeholder="请输入展示页面URL或小程序打不开时的备选URL" v-model="form.viewUrl" allow-clear></a-input>
      </a-form-item>
      <a-form-item label="排序" field="sort">
        <a-input-number :min="1" placeholder="请输入菜单排序" v-model="form.sort"></a-input-number>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { wechatMenuAppend } from '@/apis'
import { Message } from '@arco-design/web-vue'
import { reAssign } from '@/utils/common'

defineOptions({ name: 'bottomMenuEdit' })

const emit = defineEmits(['getTableData'])
const formRef = ref()
const title = computed(() => (form.menuId ? '编辑菜单' : form.pId ? '新增子菜单' : '新增菜单'))
const visible = ref(false)
const form = reactive({
  menuId: undefined,
  type: undefined,
  name: undefined,
  eventKey: undefined,
  viewUrl: undefined,
  appId: undefined,
  miniPath: undefined,
  pId: undefined,
  sort: undefined
})

// 打开编辑框并回显表单值
const addOrEdit = (item) => {
  reAssign(form, item)
  form.sort = form.sort ?? 1
  item && formRef.value?.validate()
  visible.value = true
}

// 点击确认添加/编辑
const onOk = async () => {
  const validateResult = await formRef.value?.validate()
  if (validateResult) return false
  await wechatMenuAppend(form)
  Message.success('操作成功')
  emit('getTableData')
  return true
}

defineExpose({ addOrEdit })
</script>
